package com.jaydenxiao.common.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.jaydenxiao.common.R;
import com.jaydenxiao.common.commonutils.TUtil;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.jaydenxiao.common.commonwidget.LoadingDialog;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.components.support.RxFragment;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.jessyan.autosize.utils.LogUtils;

/**
 * des:基类fragment
 * Created by xsf
 * on 2016.07.12:38
 */

public abstract class BaseFragment<V extends BaseView, T extends BasePresenter<V>> extends RxFragment implements BaseView {

    protected View rootView;
    public T mPresenter;
    //ButterKnife
    private Unbinder mUnbinder;
    protected TextView toolbar_header;
    protected Toolbar toolbar;

    protected Activity mActivity;
    protected Context mContext;
    private ImmersionBar mImmersionBar;

    private boolean mIsFirstVisible = true;

    private boolean isViewCreated = false;

    private boolean currentVisibleState = false;


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = getActivity();
        mContext = mActivity.getBaseContext();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mActivity = null;
        mContext = null;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutResource(), container, false);

            mPresenter = TUtil.getT(this, 1);
            if (mPresenter != null) {
                mPresenter.mContext = getActivity();
                mPresenter.attachView((V) this);
            }
            if (rootView.getParent() != null) {
                ((ViewGroup) rootView.getParent()).removeView(rootView);
            }
            if (container != null) {
//                CommonLogger.e("添加父类");
                container.addView(rootView);
            }
            mUnbinder = ButterKnife.bind(this, rootView);
          //  mImmersionBar = ImmersionBar.with(this);
            initView();
        }
        if (rootView.getParent() != null) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
        return rootView;
    }

    //获取布局文件
    protected abstract int getLayoutResource();


    //初始化view
    protected abstract void initView();




    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return bindToLifecycle();
    }


    //初始化toolbar
    protected void initToolbar(int title, boolean showNavigationIcon, boolean menuItemClick,
                               int menuLayout, final OnMenuClickListener onMenuClickListener) {
        initToolbar(this.getResources().getString(title), showNavigationIcon,
                menuItemClick, onMenuClickListener);
        toolbar.inflateMenu(menuLayout);
    }

    //初始化toolbar
    @SuppressWarnings("ConstantConditions")
    protected void initToolbar(String title, boolean showNavigationIcon, boolean menuItemClick,
                               final OnMenuClickListener onMenuClickListener) {
        toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        toolbar_header = (TextView) rootView.findViewById(R.id.toolbar_title_tv);
        toolbar_header.setText(title);
        setHasOptionsMenu(true);
        ((BaseActivity) mActivity).setSupportActionBar(toolbar);
        ActionBar actionBar = ((BaseActivity) mActivity).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
        if (showNavigationIcon) {
            toolbar.setNavigationIcon(R.drawable.back);
            // Menu item click 的監聽事件一樣要設定在 setSupportActionBar 才有作用
            // toolbar.setOnMenuItemClickListener(onMenuItemClick);
            //设置toolbar右侧的点击事件
            toolbar.setNavigationOnClickListener(v -> mActivity.finish());
        }
        if (menuItemClick) {
            toolbar.setOnMenuItemClickListener(item -> {
                onMenuClickListener.onItemClick(item);
                return false;
            });
        }
    }

    //点击事件的回调
    public interface OnMenuClickListener {
        void onItemClick(MenuItem item);
    }





    /**
     * 视图真正可见的时候才调用
     */

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 对于默认 tab 和 间隔 checked tab 需要等到 isViewCreated = true 后才可以通过此通知用户可见
        // 这种情况下第一次可见不是在这里通知 因为 isViewCreated = false 成立,等从别的界面回到这里后会使用 onFragmentResume 通知可见
        // 对于非默认 tab mIsFirstVisible = true 会一直保持到选择则这个 tab 的时候，因为在 onActivityCreated 会返回 false
        if (isViewCreated) {
            if (isVisibleToUser && !currentVisibleState) {
                LogUtils.e("setUserVisibleHint true");
                dispatchUserVisibleHint(true);
            } else if (!isVisibleToUser && currentVisibleState) {
                LogUtils.e("setUserVisibleHint false");
                dispatchUserVisibleHint(false);
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && mImmersionBar != null)
            mImmersionBar.init();
        LogUtils.e(getClass().getSimpleName() + "  onHiddenChanged dispatchChildVisibleState  hidden " + hidden);
        LogUtils.e("onHiddenChanged");
        if (hidden) {
            dispatchUserVisibleHint(false);
        } else {
            dispatchUserVisibleHint(true);
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        // !isHidden() 默认为 true  在调用 hide show 的时候可以使用
        if (!isHidden() && getUserVisibleHint()) {
            dispatchUserVisibleHint(true);
        }
    }




    /**
     * 统一处理 显示隐藏
     *
     * @param visible
     */
    private void dispatchUserVisibleHint(boolean visible) {
        //当前 Fragment 是 child 时候 作为缓存 Fragment 的子 fragment getUserVisibleHint = true
        //但当父 fragment 不可见所以 currentVisibleState = false 直接 return 掉
        // 这里限制则可以限制多层嵌套的时候子 Fragment 的分发
        if (visible && isParentInvisible()) return;

        //此处是对子 Fragment 不可见的限制，因为 子 Fragment 先于父 Fragment回调本方法 currentVisibleState 置位 false
        // 当父 dispatchChildVisibleState 的时候第二次回调本方法 visible = false 所以此处 visible 将直接返回
        if (currentVisibleState == visible||!isViewCreated) {
            return;
        }
        currentVisibleState = visible;
        if (visible) {
            if (mIsFirstVisible) {
                mIsFirstVisible = false;
                onFragmentFirstVisible();
            }
            onFragmentResume();
            dispatchChildVisibleState(true);
        } else {
            dispatchChildVisibleState(false);
            onFragmentPause();
        }
    }


    /**
     * 用于分发可见时间的时候父获取 fragment 是否隐藏
     *
     * @return true fragment 不可见， false 父 fragment 可见
     */
    private boolean isParentInvisible() {
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof BaseFragment) {
            BaseFragment fragment = (BaseFragment) parentFragment;
            return !fragment.isSupportVisible();
        }else {
            return false;
        }
    }

    /**
     * 当前 Fragment 是 child 时候 作为缓存 Fragment 的子 fragment 的唯一或者嵌套 VP 的第一 fragment 时 getUserVisibleHint = true
     * 但是由于父 Fragment 还进入可见状态所以自身也是不可见的， 这个方法可以存在是因为庆幸的是 父 fragment 的生命周期回调总是先于子 Fragment
     * 所以在父 fragment 设置完成当前不可见状态后，需要通知子 Fragment 我不可见，你也不可见，
     * <p>
     * 因为 dispatchUserVisibleHint 中判断了 isParentInvisible 所以当 子 fragment 走到了 onActivityCreated 的时候直接 return 掉了
     * <p>
     * 当真正的外部 Fragment 可见的时候，走 setVisibleHint (VP 中)或者 onActivityCreated (hide show) 的时候
     * 从对应的生命周期入口调用 dispatchChildVisibleState 通知子 Fragment 可见状态
     *
     * @param visible
     */
    private void dispatchChildVisibleState(boolean visible) {
        FragmentManager childFragmentManager = getChildFragmentManager();
        List<Fragment> fragments = childFragmentManager.getFragments();
        if (!fragments.isEmpty()) {
            for (Fragment child : fragments) {
                if (child instanceof BaseFragment && !child.isHidden() && child.getUserVisibleHint()) {
                    ((BaseFragment) child).dispatchUserVisibleHint(visible);
                }
            }
        }
    }

    public void onFragmentFirstVisible() {
        LogUtils.e(getClass().getSimpleName() + "  对用户第一次可见");

    }

    public void onFragmentResume() {
        LogUtils.e(getClass().getSimpleName() + "  对用户可见");
    }

    public void onFragmentPause() {
        LogUtils.e(getClass().getSimpleName() + "  对用户不可见");
    }


    private boolean isSupportVisible() {
        return currentVisibleState;
    }



    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mUnbinder != null) mUnbinder.unbind();
        if (mPresenter != null)
            mPresenter.detachView();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null)
            mImmersionBar.destroy();

    }


}
